<template>
  <div class="login-container">
    <div class="brand-container">
      <div class="logo-container">
        <i class="el-icon chat-icon"><MessageBox /></i>
      </div>
      <h1 class="brand-title">TalkFlow</h1>
      <p class="brand-subtitle">畅享高效沟通，连接美好世界</p>
    </div>
    <div class="login-box">
      <h2>用户登录</h2>
      <div class="login-tabs">
        <span 
          v-for="type in loginTypes" 
          :key="type.code"
          :class="['tab-item', { active: currentType === type.code }]"
          @click="switchLoginType(type.code)"
        >
          {{ type.description }}
        </span>
      </div>

      <div class="login-form">
        <el-form ref="loginFormRef" :model="loginForm" :rules="rules">
          <!-- TF ID登录 -->
          <template v-if="currentType === 3">
            <el-form-item prop="tfId">
              <el-input 
                v-model="loginForm.tfId" 
                placeholder="请输入TF ID"
                :prefix-icon="User"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input 
                v-model="loginForm.password" 
                type="password" 
                placeholder="请输入密码"
                :prefix-icon="Lock"
                show-password
              />
              <div class="forgot-password">
                <router-link to="/forgot-password">忘记密码？</router-link>
              </div>
            </el-form-item>
          </template>

          <!-- 邮箱密码登录 -->
          <template v-if="currentType === 1">
            <el-form-item prop="email">
              <el-input 
                v-model="loginForm.email" 
                placeholder="请输入邮箱"
                :prefix-icon="Message"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input 
                v-model="loginForm.password" 
                type="password" 
                placeholder="请输入密码"
                :prefix-icon="Lock"
                show-password
              />
              <div class="forgot-password">
                <router-link to="/forgot-password">忘记密码？</router-link>
              </div>
            </el-form-item>
          </template>

          <!-- 邮箱验证码登录 -->
          <template v-if="currentType === 2">
            <el-form-item prop="email">
              <el-input 
                v-model="loginForm.email" 
                placeholder="请输入邮箱"
                :prefix-icon="Message"
              />
            </el-form-item>
            <el-form-item prop="code">
              <div class="code-input">
                <el-input 
                  v-model="loginForm.code" 
                  placeholder="请输入验证码"
                  :prefix-icon="Key"
                />
                <el-button 
                  type="primary" 
                  :disabled="countdown > 0"
                  @click="sendVerificationCode"
                >
                  {{ countdown > 0 ? `${countdown}s后重试` : '发送验证码' }}
                </el-button>
              </div>
              <div class="forgot-password">
                <router-link to="/forgot-password">忘记密码？</router-link>
              </div>
            </el-form-item>
          </template>

          <el-form-item>
            <el-button 
              type="primary" 
              class="login-btn" 
              :loading="loading"
              @click="handleLogin"
            >
              登录
            </el-button>
          </el-form-item>
          <div class="register-link">
            没有账号？<router-link to="/register">立即注册</router-link>
          </div>
        </el-form>
      </div>
    </div>
    <div class="footer">
      <p>© 2025 TalkFlow 聊天应用 - 连接沟通，畅享交流</p>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Key, MessageBox } from '@element-plus/icons-vue'
import { login, sendEmailCode } from '@/api/user'
import { createWebSocket } from '@/utils/websocket'
import { getUnreadMessageCount } from '@/api/message'

export default {
  name: 'LoginPage',
  setup() {
    const router = useRouter()
    const loginFormRef = ref(null)
    const loading = ref(false)
    const countdown = ref(0)
    const currentType = ref(3)

    const loginForm = reactive({
      loginType: 3,
      email: '',
      tfId: '',
      password: '',
      code: ''
    })

    const rules = {
      tfId: [
        { required: true, message: '请输入TF ID', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
      ]
    }

    const loginTypes = [
      { code: 3, description: 'TF ID登录' },
      { code: 1, description: '邮箱密码登录' },
      { code: 2, description: '邮箱验证码登录' }
    ]

    const switchLoginType = (type) => {
      currentType.value = type
      loginForm.loginType = type
      resetForm()
    }

    const resetForm = () => {
      if (loginFormRef.value) {
        loginFormRef.value.resetFields()
      }
      Object.assign(loginForm, {
        loginType: currentType.value,
        email: '',
        tfId: '',
        password: '',
        code: ''
      })
    }

    const startCountdown = () => {
      countdown.value = 60
      const timer = setInterval(() => {
        if (countdown.value > 0) {
          countdown.value--
        } else {
          clearInterval(timer)
        }
      }, 1000)
    }

    const sendVerificationCode = async () => {
      try {
        await loginFormRef.value.validateField('email')
        await sendEmailCode(loginForm.email)
        ElMessage.success('验证码已发送')
        startCountdown()
      } catch (error) {
        console.error('发送验证码失败：', error)
      }
    }

    const handleLogin = async () => {
      if (!loginFormRef.value) return
      
      try {
        await loginFormRef.value.validate()
        loading.value = true
        
        console.log('发送登录请求...')
        const res = await login(loginForm)
        console.log('登录响应:', res)
        
        // 仅保存token
        localStorage.setItem('token', res.token)
        
        // 登录成功后建立WebSocket连接
        if (res.id) {
          console.log('获取到用户ID:', res.id)
          // 保存用户ID以便后续使用
          localStorage.setItem('userId', res.id)
          
          // 建立WebSocket连接
          console.log('开始建立WebSocket连接...')
          createWebSocket(res.id)
          
          // 获取未读消息数
          try {
            await getUnreadMessageCount()
          } catch (error) {
            console.error('获取未读消息数失败', error)
          }
        } else {
          console.warn('登录响应中没有用户ID')
        }
        
        ElMessage.success('登录成功')
        router.push('/home')
      } catch (error) {
        console.error('登录失败：', error)
        // API层已经显示了错误消息，这里不需要再次显示
      } finally {
        loading.value = false
      }
    }

    return {
      loginFormRef,
      loading,
      countdown,
      currentType,
      loginForm,
      rules,
      loginTypes,
      User,
      Lock,
      Message,
      Key,
      MessageBox,
      switchLoginType,
      resetForm,
      sendVerificationCode,
      handleLogin
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  padding: 20px;
}

.brand-container {
  text-align: center;
  margin-bottom: 30px;
  color: white;
}

.logo-container {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 80px;
  height: 80px;
  background-color: white;
  border-radius: 50%;
  margin-bottom: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.chat-icon {
  font-size: 40px;
  color: #764ba2;
}

.brand-title {
  font-size: 42px;
  font-weight: bold;
  margin: 0 0 10px;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.brand-subtitle {
  font-size: 16px;
  opacity: 0.9;
  margin: 0;
}

.login-box {
  width: 420px;
  padding: 40px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-weight: 500;
}

.login-tabs {
  display: flex;
  margin-bottom: 25px;
  border-bottom: 1px solid #eee;
}

.tab-item {
  flex: 1;
  padding: 12px;
  text-align: center;
  cursor: pointer;
  color: #666;
  transition: all 0.3s ease;
}

.tab-item:hover {
  color: #764ba2;
}

.tab-item.active {
  color: #764ba2;
  border-bottom: 2px solid #764ba2;
}

.code-input {
  display: flex;
  gap: 10px;
}

.code-input :deep(.el-input) {
  flex: 1;
}

.login-btn {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
  background: linear-gradient(to right, #667eea, #764ba2);
  border: none;
  transition: transform 0.3s;
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(118, 75, 162, 0.3);
}

.register-link {
  text-align: center;
  margin-top: 15px;
  font-size: 14px;
  color: #666;
}

.register-link a {
  color: #764ba2;
  text-decoration: none;
  font-weight: 500;
}

.register-link a:hover {
  text-decoration: underline;
}

.forgot-password {
  text-align: right;
  margin-top: 5px;
  font-size: 14px;
}

.forgot-password a {
  color: #764ba2;
  text-decoration: none;
}

.forgot-password a:hover {
  text-decoration: underline;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  padding: 6px 11px;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #764ba2 inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #764ba2 inset !important;
}

:deep(.el-button--primary) {
  --el-button-bg-color: #764ba2;
  --el-button-border-color: #764ba2;
  --el-button-hover-bg-color: #8a63b1;
  --el-button-hover-border-color: #8a63b1;
  --el-button-active-bg-color: #673d91;
}

.footer {
  position: absolute;
  bottom: 20px;
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
}
</style> 